package edu.zut.main.thread;

public class DeadLock {

    public static void main(String[] args) {
        People boy = new People("boy");
        People girl = new People("girl");

        new Thread(new DeadThread(boy)).start();
        new Thread(new DeadThread(girl)).start();

    }

}

//刀叉问题 模拟死锁、

class DeadThread implements Runnable{

    private People people;

    public DeadThread(People people) {
        this.people = people;
    }

    @Override
    public void run() {
        try {
            people.eatFood();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}



//叉子
class Fork{}

//刀
class Knife{}

class People{
    //模拟多人只有一组刀叉
    static Fork fork = new Fork();
    static Knife knife = new Knife();

    private String name;

    public People(String name) {
        this.name = name;
    }

    public void eatFood() throws InterruptedException {
        if (name.equals("boy")){
            synchronized (knife){
                System.out.println("boy把刀拿走了");
                Thread.sleep(1000);
            }
            synchronized (fork){
                System.out.println("boy又把叉子拿走了");
            }
        }
        if (name.equals("girl")){
            synchronized (fork){
                System.out.println("girl把叉子拿走");
                Thread.sleep(1000);
            }
            synchronized (knife){
                System.out.println("girl又把刀拿走了");
            }
        }



    }

}
